package server.communication.listeners;

import server.Server;
import server.repositories.AccountRepository;
import server.threads.ServerCommunicator;
import message.BulkUpdateRequestMessage;
import message.BulkUpdateResponseMessage;
import message.Message;
import message.ServerMessageWrapper;
import message.UpdateDataRequestMessage;
import communication.MessageListener;
import communication.MessageReceivedEvent;
import entities.Account;

public class BulkUpdateResponseListener implements MessageListener
{
	private final Server server;
	
	public BulkUpdateResponseListener(Server server)
	{
		this.server = server;
	}
	@Override
	public void messageRecieved(MessageReceivedEvent e)
	{
		ServerMessageWrapper message = ((ServerMessageWrapper) e.getMessage());
		BulkUpdateResponseMessage innerMessage = (BulkUpdateResponseMessage) message.internalMessage;
		
		for (Account account : innerMessage.getInsertedAccounts())
		{
			server.getAccountRepository().persist(account);
			System.out.println("Created: " + account.username);
		}
		
		for (Account account : innerMessage.getUpdatedAccounts())
		{
			server.getAccountRepository().persist(account);
			System.out.println("Modified: " + account.password);
		}
		
		server.bulkUpdateCompleted();
	}
	@Override
	public boolean acceptsMessage(Message message)
	{
		if (message.getClass().equals(ServerMessageWrapper.class))
			message = ((ServerMessageWrapper) message).internalMessage;
		
		return message.getClass().equals(BulkUpdateResponseMessage.class);
	}
}
